package com.agent.crm.sechdule.receiver;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import xu.ye.dao.ContactDao;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.telephony.SmsManager;
import android.widget.Toast;

import com.agent.crm.bean.MyContact;
import com.agent.crm.db.DBInitScript;
import com.agent.crm.db.DatabaseManager;
import com.agent.crm.view.R;
import com.pwp.activity.StopScheduleByNotificationActivity;
import com.pwp.dao.ScheduleDAO;
import com.pwp.vo.ScheduleVO;

public class RepeatingSMS extends BroadcastReceiver {

	DatabaseManager manager ;
	private Context mcContext;
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		/**
		 * 发送短信操作
		 */
		mcContext =context;
		if(null==manager)
		manager = new DatabaseManager(context);
		
		ScheduleVO scheduleVO = (ScheduleVO)intent.getSerializableExtra("schedule");
		Date d=new Date();
    	ScheduleDAO dao=new ScheduleDAO(context);
    	if("1".equalsIgnoreCase(scheduleVO.getScheduleCycleType())){
  			 dao.resetScheduleStatusFlags(scheduleVO.getScheduleID(),"2");
		    }
		if(d.after(formatStringToDate(scheduleVO.getScheduleEndDate()))){
			Intent intentForStop = new Intent(context,
					RepeatingAlarm.class);
	   		PendingIntent sender = PendingIntent.getBroadcast(context,
	   				scheduleVO.getScheduleID(), intentForStop, 0);
			// And cancel the alarm.
			AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
			am.cancel(sender);
			dao.resetScheduleStatusFlagsToFinished(scheduleVO.getScheduleID());
			return;
		}
		Intent sentIntent = new Intent(context,SMSSendedReceiver.class);   
		PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, sentIntent,   
		        0);   
		// register the Broadcast Receivers   
//		context.registerReceiver(new BroadcastReceiver() {   
//		    @Override  
//		    public void onReceive(Context _context, Intent _intent) {   
//		        switch (getResultCode()) {   
//		        case Activity.RESULT_OK:   
//		            Toast.makeText(_context,   
//		        "短信发送成功", Toast.LENGTH_SHORT)   
//		        .show();   
//		        break;   
//		        case SmsManager.RESULT_ERROR_GENERIC_FAILURE:   
//		        break;   
//		        case SmsManager.RESULT_ERROR_RADIO_OFF:   
//		        break;   
//		        case SmsManager.RESULT_ERROR_NULL_PDU:   
//		        break;   
//		        }   
//		    }   
//		}, new IntentFilter(SENT_SMS_ACTION));  
		String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";   
//		// create the deilverIntent parameter   
		Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);   
		PendingIntent deliverPI = PendingIntent.getBroadcast(context, 0,   
		       deliverIntent, 0);   
//		context.registerReceiver(new BroadcastReceiver() {   
//		   @Override  
//		   public void onReceive(Context _context, Intent _intent) {   
//		       Toast.makeText(_context,   
//		  "收信人已经成功接收", Toast.LENGTH_SHORT)   
//		  .show();   
//		   }   
//		}, new IntentFilter(DELIVERED_SMS_ACTION));  
		//得到所有的接受信息的对象ID
		if(null!=scheduleVO.getScheduleObjectID()&&!"".equalsIgnoreCase(scheduleVO.getScheduleObjectID())){
			SmsManager smsManager = SmsManager.getDefault();   
			String[] listObjectID =String.valueOf(scheduleVO.getScheduleObjectID()).split(",");
			List<String> listMobileNum =new ArrayList<String>();
			if("0".equalsIgnoreCase(scheduleVO.getScheduleMode())){
				//单人任务，通过objectID从人员表中查询号码
				listMobileNum=getObjectTel(listObjectID, "0");
			}else if("1".equalsIgnoreCase(scheduleVO.getScheduleMode())){
				//分类任务，通过objectID从人员表和分类表关联结果中查询号码
				listMobileNum=getObjectTel(listObjectID, "1");
			}else{
				//群组任务，通过objectID从人员表和群组表关联记过中查询号码
				listMobileNum=getObjectTel(listObjectID, "2");
			}
			if(listMobileNum.size()<=0){
				Toast.makeText(context,"短信任务:"+scheduleVO.getScheduleTitle()+",没有需要发送短信的对象", Toast.LENGTH_SHORT).show();
				return;
			}
			for (int i = 0; i < listMobileNum.size(); i++) {
				smsManager.sendTextMessage(listMobileNum.get(i), null, scheduleVO.getScheduleContent(), sentPI, deliverPI);  
			}
			//提示已发送
			Toast.makeText(context,"短信任务："+scheduleVO.getScheduleTitle()+"已发送", Toast.LENGTH_SHORT).show();
	        Intent i=new Intent(context,StopScheduleByNotificationActivity.class);
	        i.putExtra("scheduleId", scheduleVO.getScheduleID());
	        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	        i.setData(Uri.parse("custom://"+System.currentTimeMillis()));//这行代码会解决notification传到StopScheduleByNotificationActivity参数不更新问题
	        Notification n=new Notification(R.drawable.bg_tab_dial_pressed_up,scheduleVO.getScheduleTitle(), System.currentTimeMillis());
	        PendingIntent pIntent=PendingIntent.getActivity(context, 0,i, 0);
	        n.defaults=Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE;
	        n.setLatestEventInfo(context,"短信任务："+scheduleVO.getScheduleTitle()+"已发送",scheduleVO.getScheduleContent(), pIntent);
	        NotificationManager nm=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
	        nm.notify(scheduleVO.getScheduleID(), n);
		}
		
	}
	
	
	private List<String> getObjectTel(String[] listObjectID,String mode){
		ContactDao cDao =new ContactDao(mcContext);
		SQLiteDatabase sqlLite = manager.getWritableDatabase();
		List<String> list = new ArrayList<String>();
		if("0".equalsIgnoreCase(mode)){
			for (int i = 0; i < listObjectID.length; i++) {
				Cursor cursor = sqlLite.query(DBInitScript.Table_ContactsInfo, new String[]{"mobile_phone"}, " contacts_id =?", new String[]{listObjectID[i]}, null, null, null, null);
				int count = cursor.getCount();
			    if(count == 0){
		        }else{
		        	while (cursor.moveToNext()) {
		        		String mobilePhone = cursor.getString(cursor.getColumnIndex("mobile_phone"));
			        	list.add(mobilePhone);
					}
		        }
			    cursor.close();
			}
		}
		if("1".equalsIgnoreCase(mode)){
			for (int i = 0; i < listObjectID.length; i++) {
				List<MyContact> contact=cDao.getContactsByTypeId(Integer.valueOf(listObjectID[i]));
				if(null==contact){
					break;
				}
				for (int j = 0; j < contact.size(); j++) {
					list.add(contact.get(j).getMobilePhone());
				}
			}
		}
		if ("2".equalsIgnoreCase(mode)) {
			for (int i = 0; i < listObjectID.length; i++) {
				List<MyContact> contact=cDao.getContactsByGroupId(Integer.valueOf(listObjectID[i]));
				if(null==contact){
					break;
				}
				for (int j = 0; j < contact.size(); j++) {
					list.add(contact.get(j).getMobilePhone());
				}
			}
		}
		sqlLite.close();
		return list;
	}

	private Date formatStringToDate(String str){
		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			return format.parse(str);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			return format.parse(format.format(new Date()));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new Date();
	}
}
